import PySimpleGUI as sg
from obsws_python import ReqClient

# 设置主题
sg.theme('DarkBlue3')

# 默认片段
default_segments = {1: 0, 2: 60_000, 3: 120_000}

# 布局
layout = [
    [sg.Text('AI无人直播切片控制器', font=('Arial', 16, 'bold'), justification='center', expand_x=True)],

    [sg.Frame('OBS 配置', [
        [sg.Text('IP 地址', size=(12, 1)), sg.Input('192.168.0.111', key='host')],
        [sg.Text('端口', size=(12, 1)), sg.Input('4455', key='port')],
        [sg.Text('密码', size=(12, 1)), sg.Input('', key='password', password_char='*')],
        [sg.Text('媒体源名', size=(12, 1)), sg.Input('11', key='source')],
        [sg.Text('', size=(12, 1)),
         sg.Text('说明: 填写 OBS 运行机器的局域网 IP、端口、密码和媒体源名称', text_color='black', font=('Arial', 9))]
    ], font=('Arial', 11))],

    [sg.Frame('片段配置 (编号:起始秒, 逗号分隔)', [
        [sg.Multiline('1:0\n2:60\n3:120', key='segments', size=(30, 5))],
        [sg.Text('', size=(1, 1)),
         sg.Text('说明: 每行输入一个片段编号和起始秒，单位为秒', text_color='black', font=('Arial', 9))]
    ], font=('Arial', 11))],

    [sg.Frame('播放控制', [
        [sg.Text('片段编号'), sg.Input(key='play_segment', size=(5, 1)),
         sg.Button('播放', button_color=('white', 'green'))],
        [sg.Text('', size=(1, 1)),
         sg.Text('说明: 输入你想播放的片段编号，然后点击播放', text_color='black', font=('Arial', 9))]
    ], font=('Arial', 11))],

    [sg.Text('_' * 50)],
    [sg.Text('© 2025 重庆激发科技有限公司 版权所有', font=('Arial', 9), text_color='black', justification='center',
             expand_x=True)],
    [sg.Button('退出', button_color=('white', 'firebrick'))]
]

window = sg.Window('AI无人直播切片控制器', layout, finalize=True)

# 客户端初始化为 None
client = None


def parse_segments(text):
    segs = {}
    for line in text.strip().split('\n'):
        if ':' in line:
            num, time_sec = line.split(':')
            segs[int(num.strip())] = int(float(time_sec.strip()) * 1000)  # 秒转毫秒
    return segs


while True:
    event, values = window.read()
    if event in (sg.WINDOW_CLOSED, '退出'):
        break
    elif event == '播放':
        host = values['host']
        port = int(values['port'])
        password = values['password']
        source = values['source']
        segments = parse_segments(values['segments'])
        seg_num_text = values['play_segment'].strip()
        if not seg_num_text.isdigit():
            sg.popup_error('请输入有效的片段编号！')
            continue
        seg_num = int(seg_num_text)
        if seg_num not in segments:
            sg.popup_error(f'片段 {seg_num} 不存在！')
            continue
        # 创建客户端（同步）
        if client is None:
            client = ReqClient(host=host, port=port, password=password)
        start_time = segments[seg_num]
        # 跳转播放
        client.set_media_input_cursor(source, start_time)
        sg.popup(f'✅ 已切换到片段 {seg_num}，起始 {start_time / 1000:.1f} 秒')

window.close()
